#!/usr/bin/env python
from flask import Flask,request,make_response,render_template
from flask_cors import CORS
from datasource import get_device_addr
import sqlite3
import base64
import numpy as np
import face_model
import cv2
import shutil
import os
import argparse
import json

os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT']='0'
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_argument('--image-size', default='112,112', help='')
parser.add_argument('--model', default='model/model-r100-ii/model,0', help='path to load model.')
parser.add_argument('--ga-model', default='ga-model/model,0', help='path to load model.')
parser.add_argument('--gpu', default=0, type=int, help='gpu id')
parser.add_argument('--det', default=2, type=int, help='mtcnn option, 1 means using R+O, 0 means detect from begining,2 meanus retinaface-r50')
parser.add_argument('--flip', default=0, type=int, help='whether do lr flip aug')
parser.add_argument('--threshold', default=1.24, type=float, help='ver dist threshold')
args = parser.parse_args()

model = face_model.FaceModel(args)

app=Flask(__name__)
CORS(app)

def generate_no():
    conn=sqlite3.connect('test.db')
    c=conn.cursor()
    userId=c.execute('select Id from sys_user order by Id desc limit 1').fetchone()[0]+1
    return userId

def store_user_to_sqlite(no,name,sex,fea):
    conn=sqlite3.connect('test.db')
    c=conn.cursor()
    result=c.execute('insert into sys_user(Id,name,feature) values(?,?,?)',(no,name,fea))
    conn.commit()

def get_feature_face_from_file(no,img):
    img=img.split(',')[1]
    img=base64.b64decode(img)
    img_array=np.fromstring(img,np.uint8)
    img=cv2.imdecode(img_array,cv2.COLOR_RGB2BGR)
    cv2.imwrite('static/img/pic0/'+str(no)+'.jpg',img)
    shutil.copyfile('static/img/pic0/'+str(no)+'.jpg','static/img/pic1/'+str(no)+'.jpg')
    box, img = model.get_input(img)
    fea = model.get_feature(img)
    return box, fea

@app.route('/monitor')
def index0():
    return "需要传入设备ID！"


@app.route('/monitor/<device_id>')
def index(device_id):
    '''
    请求数据。
    :param device_id:
    :return:
    '''
    device_addr = get_device_addr(device_id)
    return render_template('index.html', device_addr=device_addr)


@app.route('/manager/register',methods=['GET','POST'])
def register():
    if request.method=='GET':
        no=generate_no()
        return render_template('register.html',no=no)
    else:
        data=request.form
        name=data['name']
        no=data['no']
        sex=data['sex']
        img=data['img']
        _,fea=get_feature_face_from_file(no,img)
        feature_str = json.dumps(fea.tolist())
        store_user_to_sqlite(int(no),name,sex,feature_str)
        return '注册成功！'


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8099, debug=False)
